package com.example.xmlpullparserdemo;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XMLParserActivity extends AppCompatActivity {

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
        setContentView(R.layout.activity_main);
        Button btn = (Button) findViewById(R.id.bnt);
        final ListView list = (ListView) findViewById(R.id.list);
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                FileInputStream fis = null;
                try {
                    if (!Environment.getExternalStorageState().equals(
                            Environment.MEDIA_MOUNTED)) {
                        Toast.makeText(XMLParserActivity.this, "未检测到SD卡",
                                Toast.LENGTH_LONG).show();
                        return;
                    }
                    File sdcard = Environment.getExternalStorageDirectory();
                    fis = new FileInputStream(sdcard.getCanonicalPath()
                            + "/books.xml");
                    Log.v("debug", "OK");
                    List<Map<String, Object>> data = parseXml(fis);
                    SimpleAdapter sa = new SimpleAdapter(XMLParserActivity.this,
                            data, R.layout.book_line, new String[]{"name",
                            "date", "price"}, new int[]{R.id.name,
                            R.id.date, R.id.price});
                    list.setAdapter(sa);
                } catch (Exception e) {
                    // TODO: handle exception
                    Log.v("debug", "file not open");
                } finally {
                    try {
                        fis.close();
                    } catch (Exception e2) {
                        // TODO: handle exception
                    }
                }

            }
        });

    }

    public List<Map<String, Object>> parseXml(InputStream is) throws Exception {

        List<Map<String, Object>> result = null;
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        XmlPullParser xpp = factory.newPullParser();
        xpp.setInput(is, "UTF-8");
        int eventType = xpp.getEventType();
        HashMap<String, Object> item = null;
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_DOCUMENT) {
                result = new ArrayList<Map<String, Object>>();
            } else if (eventType == XmlPullParser.START_TAG) {
                if ("book".equals(xpp.getName())) {
                    item = new HashMap<String, Object>();
                    item.put("price", xpp.getAttributeValue(null, "price"));
                    item.put("date", xpp.getAttributeValue(null, "出版日期"));
                    item.put("name", xpp.nextText());

                    result.add(item);
                }
            }

            eventType = xpp.next();
        }

        return result;
    }
}
